import axios from 'axios'
import {message} from 'antd'

const baseURL = 'http://localhost:8090'
// const baseURL = 'http://121.5.128.248:8090'
axios.defaults.baseURL = baseURL;

export {axios, baseURL}

// 配置
message.config({
  // 自动关闭时间
  // duration: 0.5,
  // 最大显示条数
  maxCount: 1,
});

export function ShowLoading(msg = "加载中...") {
  message.destroy()
  message.loading({content: msg, key: 'loading', duration: 0})
}

export function ShowError(msg = "未知错误") {
  message.destroy()
  message.error({content: msg, key: 'error', duration: 2})
}

export function ShowSuccess(msg = "请求成功") {
  message.destroy('success')
  message.success({content: msg, key: 'success', duration: 1})
}

// axios 请求拦截器
axios.interceptors.request.use(function (config) {
  ShowLoading()
  const token = sessionStorage.getItem("token")
  if (token) {
    config.headers.token = token;
  }
  return config;
}, function (error) {
  ShowError('请求失败')
  return Promise.reject(error);
});

// axios 响应拦截器
axios.interceptors.response.use(function (response) {
  message.destroy()
  if (response.data.code === 200) {
    ShowSuccess(response.data.msg || "请求成功")
  } else {
    ShowError(response.data.msg || "请求失败")
  }
  return response;
}, function (error) {
  ShowError('响应失败', error)
  return Promise.reject(error);
});


// GET
export const get = function (url, params, headers) {
  return new Promise(function (resolve, reject) {
    axios({
      url,
      method: "GET",
      params,
      headers
    })
      .then(res => {
        resolve(res.data) // 返回数据
      })
      .catch(err => {
        reject(err) // 返回错误
      })
  })
}
// POST
export const post = function (url, data, headers) {
  return new Promise(function (resolve, reject) {
    axios({
      url,
      method: "POST",
      data,
      headers
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
